import { useState, useEffect } from 'react'
import style from './index.module.scss'
import { Toast, Image, List, Button } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { GetUser, UserLogout } from '@/api/mine'
import { useActivate, useUnactivate } from 'react-activation'
import HeaderView from '@/components/Header/index'
import Bottom from '@/components/Bottom/index'
import LoadingView from '@/components/Loading/index'
import { saveToken } from '@/reduxToolkit/reducers/token'
import { useDispatch } from 'react-redux'
import { removeCookie } from '@/utils/cookie'

const Mine = () => {
  const [flag, setFlag] = useState(true)
  const [loadingCode, setLoadingCode] = useState(1)    
  const [user, setUser] = useState({ // 用户信息
    img: '',
    name: '',
    email: ''
  })
  const [count, setCount] = useState(0)
  const navigate = useNavigate()
  const dispatch = useDispatch()

  // 数据初始化
  const init = async () => {
    const res = await GetUser().catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
      if (err.status === 401) Toast.show({icon: 'success', content: '请先登录呀', duration: 1500, maskClickable: false, afterClose: () => {
        navigate('/login', {state: {fromPath: 'mine'}})
      }})
    })

    if(res?.status === 200) {
      setFlag(false)
      setUser({img: res.data.avatar_url, name: res.data.name, email: res.data.email})
    }  
  }

  useEffect(() => {
    init()
  }, [])

  const loginOut = async () => { // 退出
    const res = await UserLogout().catch((error: { code: string }) => {
      if (error.code === 'ECONNABORTED' || error.code === "ERR_NETWORK") Toast.show({icon: 'fail', content: '请求超时', duration: 1500})
    })

    if(res?.status === 204){
      Toast.show({
      icon: 'success',
        content: '退出成功',
        maskClickable: false,
        afterClose: async() => {
          navigate('/home')
          dispatch(saveToken(null)) // 存储token
          removeCookie('token')
          removeCookie('ID')
          removeCookie('fromPath')
          removeCookie('total')
          removeCookie('cartNum')
        }
      })
    }
}

  useActivate(() => {
    setFlag(false)
    if(count === 1) {
      init()
    }
  })

  useUnactivate(() => {
    setCount(count + 1)
  })

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title='个人中心' backIcon={false} backPath=''></HeaderView>

      {/* 用户信息 */}
      <div className={style.content}>
        <div className={style.headerImg}>
           <div className={style.imgLeft}>
              <Image src={user.img}/>
           </div>
           <div className={style.imgRight}>
            <p>昵称: {user.name}</p>
            <p>账号: {user.email}</p>
            <p>个性签名: 希望我有钱, 让爸妈过的好</p>
           </div>
        </div>
      </div>

      <div className={style.mineList}>
        <List>
          <List.Item arrowIcon onClick={() => navigate('/collect')}>我的收藏</List.Item>
          <List.Item arrowIcon>我的订单</List.Item>
          <List.Item arrowIcon>账号管理</List.Item>
          <List.Item arrowIcon onClick={() => navigate('/address')}>地址管理</List.Item>
          <List.Item arrowIcon>关于我们</List.Item>
        </List>

        <div className={style.btn}>
          <Button color='success' block shape="rounded" onClick={() => loginOut()} style={{"--background-color": '#07c160'}}>退出</Button>
        </div>
      </div>

      {/* 底部tabbar */}
      <Bottom></Bottom>

      {/* 加载中或者加载超时 */}
      {flag && <LoadingView loadingCode={loadingCode}></LoadingView>}
    </>
  )
}

export default Mine